package com.lzb.compressmaster.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.compressmaster.BaseAc;
import com.lzb.compressmaster.Content;
import com.lzb.compressmaster.R;
import com.lzb.compressmaster.adapter.PicCompressListAdapter;
import com.lzb.compressmaster.adapter.PicCompressTypeAdapter;
import com.lzb.compressmaster.adapter.PicOutputFormatAdapter;
import com.lzb.compressmaster.bean.PicCompressTypeBean;
import com.lzb.compressmaster.bean.PicOutputFormatBean;
import com.lzb.compressmaster.databinding.ActivityPictureCompressBinding;
import com.lzb.compressmaster.dialog.FileSizeDialog;
import com.lzb.compressmaster.dialog.RenameDialog;
import com.lzb.compressmaster.dialog.WarmerTipDialog;
import com.lzb.compressmaster.utils.CompressConfigBuilder;
import com.lzb.compressmaster.utils.ImageCompressor;
import com.sztle.admodule.apiprocessor.OutRewardAdApi;
import com.sztle.admodule.apiprocessor.listener.IOutRewardCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PictureCompressActivity extends BaseAc<ActivityPictureCompressBinding> implements View.OnClickListener, OnItemChildClickListener, OnItemClickListener {

    public static List<String> listPath = new ArrayList<>();
    private PicCompressListAdapter picCompressListAdapter;
    private PicCompressTypeAdapter typeAdapter;
    private PicOutputFormatAdapter formatAdapter;
    private ImageCompressor.CompressConfig compressConfig;
    private String sizeUnit, newName;
    private int typePos, formatPos;

    @Override
    protected int onCreate() {
        return R.layout.activity_picture_compress;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPictureCompressBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvAddPicture.setOnClickListener(this);
        mDataBinding.tvFileName.setOnClickListener(this);
        mDataBinding.tvSizeUnit.setOnClickListener(this);
        mDataBinding.ivSizeTip.setOnClickListener(this);
        mDataBinding.ivAspectRatio.setOnClickListener(this);
        mDataBinding.tvStartCompress.setOnClickListener(this);

        mDataBinding.rvPictureList.setLayoutManager(new GridLayoutManager(mContext, 3));
        picCompressListAdapter = new PicCompressListAdapter();
        mDataBinding.rvPictureList.setAdapter(picCompressListAdapter);
        picCompressListAdapter.addChildClickViewIds(R.id.ivPicCompressListItemDelete);
        picCompressListAdapter.setOnItemChildClickListener(this);

        mDataBinding.rvCompressType.setLayoutManager(new GridLayoutManager(mContext, 4));
        typeAdapter = new PicCompressTypeAdapter();
        mDataBinding.rvCompressType.setAdapter(typeAdapter);
        typeAdapter.setOnItemClickListener(this);

        mDataBinding.rvFormatList.setLayoutManager(new GridLayoutManager(mContext, 4));
        formatAdapter = new PicOutputFormatAdapter();
        mDataBinding.rvFormatList.setAdapter(formatAdapter);
        formatAdapter.setOnItemClickListener(this);

        mDataBinding.sbProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mDataBinding.tvSizeProgress.setText(progress + getString(R.string.unit_percent));
                compressConfig.setScalePercent(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tvAddPicture) {//添加图片
            Intent intent = new Intent(this, AddPictureActivity.class);
            intent.putExtra(Content.Again, "Again");
            startActivityForResult(intent, Content.ADD_PICTURE);
        } else if (id == R.id.tvFileName) {//文件名
            showRenameDialog();
        } else if (id == R.id.tvSizeUnit) {//文件大小单位
            showFileSizeDialog();
        } else if (id == R.id.ivSizeTip) {//文件大小提示
            showWarmerTipDialog();
        } else if (id == R.id.llAspectRatio) {//固定宽高比
            if (compressConfig.isKeepAspectRatio()) {
                compressConfig.setKeepAspectRatio(false);
                mDataBinding.ivAspectRatio.setImageResource(R.drawable.awxz);
            } else {
                compressConfig.setKeepAspectRatio(true);
                mDataBinding.ivAspectRatio.setImageResource(R.drawable.axuanz);
            }
        } else if (id == R.id.tvStartCompress) {//开始压缩
            String size = mDataBinding.etFileSize.getText().toString();
            String width = mDataBinding.etSpecifiedWidth.getText().toString();
            String height = mDataBinding.etSpecifiedHeight.getText().toString();
            if (compressConfig.getCompressType() == ImageCompressor.CompressType.SIZE) {
                if (TextUtils.isEmpty(size)) {
                    ToastUtils.showShort(getString(R.string.please_input_target_file_size));
                    return;
                } else {
                    long targetSize = 0;
                    if (sizeUnit.equals(getString(R.string.unit_kb))) {
                        targetSize = Integer.parseInt(size) * 1024L;
                    } else {
                        targetSize = Integer.parseInt(size) * 1024L * 1024L;
                    }
                    compressConfig.setTargetSize(targetSize);
                }
            }
            if (TextUtils.isEmpty(width)) {
                ToastUtils.showShort(getString(R.string.please_input_width));
                return;
            }
            if (TextUtils.isEmpty(height)) {
                ToastUtils.showShort(getString(R.string.please_input_height));
                return;
            }
            compressConfig.setWidth(Integer.parseInt(width));
            compressConfig.setHeight(Integer.parseInt(height));
            OutRewardAdApi.showRewardAd(this, "picture_compress", new IOutRewardCallback() {
                @Override
                public void onRewardEnd() {
                    startCompress();
                }
            });
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == typeAdapter) {
            typeAdapter.getItem(typePos).setSelected(false);
            typePos = position;
            typeAdapter.getItem(position).setSelected(true);
            typeAdapter.notifyDataSetChanged();
            compressConfig.setCompressType(typeAdapter.getItem(position).getCompressType());
            updateView();
        } else if (adapter == formatAdapter) {
            formatAdapter.getItem(formatPos).setSelected(false);
            formatPos = position;
            formatAdapter.getItem(position).setSelected(true);
            formatAdapter.notifyDataSetChanged();
            compressConfig.setOutputFormat(formatAdapter.getItem(position).getOutputFormat());
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.ivPicCompressListItemDelete) {//删除
            listPath.remove(position);
            picCompressListAdapter.setList(listPath);
        }
    }

    @Override
    protected void initData() {
        newName = FileUtils.getFileNameNoExtension(listPath.get(0));
        mDataBinding.tvFileName.setText(newName);
        mDataBinding.tvOriginalFileSize.setText(ConvertUtils.byte2FitMemorySize(new File(listPath.get(0)).length(), 2));
        sizeUnit = getString(R.string.unit_kb);

        picCompressListAdapter.setList(listPath);

        List<PicCompressTypeBean> listType = new ArrayList<>();
        listType.add(new PicCompressTypeBean(ImageCompressor.CompressType.SMART, true));
        listType.add(new PicCompressTypeBean(ImageCompressor.CompressType.ADVANCED, false));
//        listType.add(new PicCompressTypeBean(ImageCompressor.CompressType.SIZE, false));
        listType.add(new PicCompressTypeBean(ImageCompressor.CompressType.PIXEL, false));
        typeAdapter.setList(listType);

        List<PicOutputFormatBean> listFormat = new ArrayList<>();
        listFormat.add(new PicOutputFormatBean(ImageCompressor.OutputFormat.ORIGINAL, true));
        listFormat.add(new PicOutputFormatBean(ImageCompressor.OutputFormat.PNG, false));
        listFormat.add(new PicOutputFormatBean(ImageCompressor.OutputFormat.JPG, false));
        listFormat.add(new PicOutputFormatBean(ImageCompressor.OutputFormat.WEBP, false));
        formatAdapter.setList(listFormat);

        compressConfig = CompressConfigBuilder.smart()
                .setFormat(ImageCompressor.OutputFormat.ORIGINAL)
                .setQuality(2)
                .setSuffix("")
                .build();

        mDataBinding.etSpecifiedWidth.setText(compressConfig.getWidth() + "");
        mDataBinding.etSpecifiedHeight.setText(compressConfig.getHeight() + "");
        mDataBinding.sbProgress.setProgress((int) compressConfig.getScalePercent());
        mDataBinding.tvSizeProgress.setText((int) compressConfig.getScalePercent() + getString(R.string.unit_percent));
    }

    private void startCompress() {
        ImageCompressor.compressImages(mContext, listPath, compressConfig, new ImageCompressor.CompressCallback() {
            @Override
            public void onProgress(int current, int total, String fileName) {
                showDialog(getString(R.string.compress_ing));
            }

            @Override
            public void onComplete(List<ImageCompressor.CompressResult> results) {
                String suffix = FileUtils.getFileExtension(results.get(0).getOutputPath());
                boolean isSuc = FileUtils.rename(results.get(0).getOutputPath(), newName + "." + suffix);
                if (isSuc) {
                    results.get(0).setOutputPath(PathUtils.getFilesPathExternalFirst() + Content.myPictureCompress + "/" + newName + "." + suffix);
                }
                dismissDialog();
                PictureCompressSucActivity.listResult = results;
                startActivity(PictureCompressSucActivity.class);
            }

            @Override
            public void onError(String error) {
                dismissDialog();
                ToastUtils.showShort(error);
            }
        });
    }

    private void updateView() {
        mDataBinding.llOutputSize.setVisibility(View.GONE);
        mDataBinding.llSpecifiedSize.setVisibility(View.GONE);
        mDataBinding.llSpecifiedPixel.setVisibility(View.GONE);
        switch (compressConfig.getCompressType()) {
            case ADVANCED:
                mDataBinding.llOutputSize.setVisibility(View.VISIBLE);
                break;
            case SIZE:
                mDataBinding.llSpecifiedSize.setVisibility(View.VISIBLE);
                break;
            case PIXEL:
                mDataBinding.llSpecifiedPixel.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void showFileSizeDialog() {
        FileSizeDialog dialog = new FileSizeDialog(mContext);
        dialog.setSelPosition(mDataBinding.tvSizeUnit.getText().toString().equals(getString(R.string.unit_kb)) ? 0 : 1);
        dialog.setListener(new FileSizeDialog.Ilistener() {
            @Override
            public void clickConfirm(String name) {
                mDataBinding.tvSizeUnit.setText(name);
                sizeUnit = name;
            }
        });
        dialog.show();
    }

    private void showWarmerTipDialog() {
        WarmerTipDialog dialog = new WarmerTipDialog(mContext);
        dialog.show();
    }

    private void showRenameDialog() {
        RenameDialog renameDialog = new RenameDialog(mContext);
        renameDialog.setName(newName);
        renameDialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                newName = name;
                mDataBinding.tvFileName.setText(newName);
            }
        });
        renameDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<String> list = data.getStringArrayListExtra(Content.path);
            if (requestCode == Content.ADD_PICTURE) {
                listPath.addAll(list);
            }
            picCompressListAdapter.setList(listPath);
        }
    }
}